package net.zhengxinyun.performance.controller.login;


import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.DepartmentFilter;
import net.zhengxinyun.performance.filter.UserFilter;
import net.zhengxinyun.performance.service.Check.CheckService;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.RolePerService;
import net.zhengxinyun.performance.service.login.TokenService;
import net.zhengxinyun.performance.service.login.UserService;
import net.zhengxinyun.performance.service.setTime.SetTimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Auther: hyp
 * @Date: 2018/10/30 14:47
 */
@RestController
@RequestMapping("/Login")
public class LoginController {

    private LoginService loginService;
    private TokenService tokenService;
    private UserService userService;
    private CheckService checkService;
    private DepartmentService departmentService;

    @Autowired
    private SetTimeService setTimeService;


    @Autowired
    private RolePerService rolePerService;

    @Autowired
    public LoginController(LoginService loginService, TokenService tokenService, UserService userService, CheckService checkService, DepartmentService departmentService) {
        this.loginService = loginService;
        this.tokenService = tokenService;
        this.userService = userService;
        this.checkService = checkService;
        this.departmentService = departmentService;
    }

    @PostMapping("/loginGetToken")
    public Result<String> loginGetToken(@RequestBody UserFilter userFilter) {
        TokenEntity token = null;
        try {
            token = loginService.loginGetToken(userFilter);
        } catch (Exception e) {

        }
        if (token == null){
            return ResultUtils.getResults(Result.Status.ERROR,"用户名密码错误");
        }else {
            return ResultUtils.getResults(Result.Status.SUCCESS,token.getValue());
        }
    }

    @PostMapping("/loginUserInfo")
    public Result<HashMap<String, Object>> loginGetUserInfo(@RequestBody TokenEntity tokenEntity, HttpServletRequest request){
        if (tokenEntity == null){
            return ResultUtils.getResults(Result.Status.OVERTIME,"没有token",null);
        }
        UserEntity userEntity = loginService.getUserByToken(tokenEntity);
        if (userEntity == null){
            return ResultUtils.getResults(Result.Status.OVERTIME,"没有token",null);
        }
        /**
         * 所有部门单位
         */
        List<DepartmentEntity> departmentList = departmentService.selectForDepartment(null,null);
        HashMap<String,String> nameToCode = new HashMap<>();
        HashMap<String,String> codeToName = new HashMap<>();
        for(DepartmentEntity item: departmentList)
        {
           // nameToCode.put(item.getDepartAddr(),item.getDepartcode());
            codeToName.put(item.getDepartcode(),item.getDepartAddr());
        }
        /**
         * 下拉框需要的部门单位
         */
        DepartmentFilter departmentFilter = new DepartmentFilter();
        if(!"admin".equals(userEntity.getUserPermissions()))
        {
            departmentFilter.setDepartcode(userEntity.getDepartcode());
        }
        List<DepartmentFilter> departments= departmentService.query(departmentFilter);


        HashMap<String,Object> userMap = new HashMap<>();
        String[] role = new String[]{userEntity.getUserPermissions()};
        //查看用户是否有需要提醒的查访核验项目
       // String[] roles ={"1","2","3","4","5","6","7","8","9","10"};
      /*  if (!"admin".equals(userEntity.getUserPermissions())){
            CheckFilter checkFilter = new CheckFilter();
            checkFilter.setAddressee(userEntity.getUserDepartment());
            checkFilter.setStatus("0");
            List<CheckFilter> list = checkService.query(checkFilter,userEntity);
            userMap.put("emailWarning",list.size());
        }*/


        //登录菜单权限
        List<String> listRights = new ArrayList<>();
        String str =null;
        if(ObjectUtils.isBlank(userEntity.getRoleid()))
        {
             str  = userEntity.getRoleRight();
            userMap.put("btnaccess",StringUtils.isBlank(userEntity.getBtnRight())?"":userEntity.getBtnRight() );

        }else {
            RolePerEntity userRole  = rolePerService.selectByPrimaryKey(userEntity.getRoleid());
            if (ObjectUtils.isBlank( userRole)){
                userMap.put("access",listRights );//用户权限
                userMap.put("btnaccess","");
            }else {
                str  = userRole.getRoleRight();
                userMap.put("btnaccess",StringUtils.isBlank(userRole.getBtnRight())?"":userRole.getBtnRight() );

            }
        }

        if (StringUtils.isBlank(str)   )
        {
            userMap.put("access",listRights );//用户权限

        }
        else {
            String[] rights =str.split(",");
            for (String  item: rights)
            {
                listRights.add(item);
            }
            userMap.put("access",listRights);//用户权限
        }


        /**
         * 登录按钮权限
         */

        userMap.put("name",userEntity.getUserName());//用户账户
        userMap.put("user_id",userEntity.getId());//用户id
        userMap.put("department",codeToName.get(userEntity.getDepartcode()));
        userMap.put("token",tokenEntity.getValue());

        userMap.put("departmentList",departments);
      /*  if ("admin".equals(userEntity.getUserPermissions())){
            userMap.put("role","管理员");
        }else if ("responsible".equals(userEntity.getUserPermissions())){
            userMap.put("role","责任人");
        }else if ("agent".equals(userEntity.getUserPermissions())){
            userMap.put("role","经办人");
        }*/
        userMap.put("role",userEntity.getNickName());
        userMap.put("roleAccess",userEntity.getUserPermissions());

        //保存登录次数
        LoginLog logs  = new LoginLog();
        logs.setUserid(userEntity.getId());
        logs.setLoginDate(DateUtils.getCurrentDate());
        logs.setLoginTime(DateUtils.getCurrentTime());
        String ip = request.getHeader("x-forwarded-for");
        if(StringUtils.isBlank(ip))
        {
            ip =request.getRemoteAddr();
        }
        logs.setIpAddr(ip);
        userService.saveloginLog(logs);
        UserFilter userfi=  userService.selectByUserId(userEntity.getId());
        userMap.put("departType",userfi.getDepartType());
        userMap.put("isManager",userEntity.getIsManger());
        userMap.put("departCode",userEntity.getDepartcode());
        /**
         * 设置最新的年份
         */
        SetTimeEntity time = setTimeService.findByIndexClass("3");
        request.getSession().setAttribute("currentYear",time.getStartTime());
        return ResultUtils.getSuccessResults(userMap);
    }

    @PostMapping("/exit")
    public Result<String> exit(@RequestBody TokenEntity tokenEntity){
        if (tokenService.compareToken(tokenEntity.getValue())){
            tokenService.delete(tokenEntity);
            return ResultUtils.getSuccessResults();
        }else {
            return ResultUtils.getResults(Result.Status.OVERTIME);
        }
    }
}

